﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Utils;

namespace vueweb.Controllers
{
	[Route("user")]
	public class UserController : BaseController
	{
		[Route("login")]
		[DirectAccessAction]
		[HttpPost]
		public IActionResult Login([FromBody] JsonElement input)
		{
			string username = input.GetProperty("username").GetString();
			string pwd = input.GetProperty("password").GetString();
			string md5 = CommonTools.MD5(pwd);
			SysUserEntity sysUserEntity = new SysUserEntity();
			IsDevLogined = false;
			bool isDev = username.Trim().ToLower() == CommonTools.Config.GetSection("root:dev:user").Get<string>().Trim().ToLower();
			if (isDev)
			{
				if (md5 == CommonTools.Config.GetSection("root:dev:pwd").Get<string>())
				{
					sysUserEntity.UserGuid = Guid.Empty.ToString();
					sysUserEntity.UserName = sysUserEntity.UserUid = username.Trim();
					CurrentLoginUser = sysUserEntity;
					IsDevLogined = true;
					return new JsonResult(new
					{
						code = 20000,
						path = "/",
						token = Token
					});
				}
				else
				{
					string message = "开发用户密码错误";
					return new JsonResult(new
					{
						code = 30000,
						message
					});
				}
			}

			sysUserEntity.Msg = "我是" + username;
			sysUserEntity.UserUid = sysUserEntity.UserName = username;
			
			CurrentLoginUser = sysUserEntity;

			return new JsonResult(new
			{
				code = 20000,
				path = "/",
				token = Token
			});
		}

		[Route("info")]
		[HttpGet]
		public IActionResult GetUserInfo()
		{
			return Json(new
			{
				code = 20000,
				roles = new string[] { "admin", "editor" },//用户的菜单通过后台控制，所以返回所有角色，让前台显示所有菜单
				name = CurrentLoginUser.UserName,
				avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
				introduction = $"当前用户：{CurrentLoginUser.UserUid}，{(IsDevLogined ? "是" : "不是")}开发用户。",
				isDev = IsDevLogined
			});
		}

		[Route("logout")]
		[DirectAccessAction]
		[HttpGet]
		public IActionResult Logout()
		{			
			CurrentLoginUser = null;
			return Json(new { code = 20000 });
		}

		[Route("menuinfo")]
		[HttpGet]
		public IActionResult MenuInfo()
		{
			JObject menu = new JObject();
			menu.Add("code", 20000);
			menu.Add("data", new JArray());
			return Content(menu.ToString(), JsonContentType);
		}
	}
}
